#pragma once

#include <QVector>
#include <QWidget>
#include <QDebug>

template <typename T>
class OPeratorinter
{
public:
	OPeratorinter() {}

	~OPeratorinter()
	{
		clearAllItems();
	}

	T* getSelect()
	{
		return getItem(m_currentIndex);
	}

	int getSelectIndex()
	{
		return m_currentIndex;
	}

	void setSelect(int index)
	{
		auto item = getItem(index);
		//auto item = firstItem();
		qDebug() << item;
		if (item)
		{
			item->setSelect(true);
			m_currentIndex = index;
		}
	}

	void setSelect(T* item)
	{
		setSelect(getIndex(item));
	}

	int getIndex(T* item)
	{
		for (int i = 0;i < m_items.size(); ++i)
		{
			if (item == m_items[i])
			{
				return i;
			}
		}
		return 0;
	}

	void selectFirstItem()
	{
		if (m_items.size() >= 0)
		{
			setSelect(1);
		}
	}

	T* getItem(int index)
	{
		if (index < 0 || index >= m_items.size())
			return nullptr;
		return m_items[index];
	}

	T* firstItem()
	{
		return m_items.front();
	}

	void addItem(T* item)
	{
		m_items.push_back(item);
	}

	void left()
	{
		auto currentItem = getItem(m_currentIndex);
		if (currentItem)
		{
			currentItem->setSelect(false);
		}
		for (int i = m_currentIndex - 1; i >= 0; --i)
		{
			auto nextItem = getItem(i);
			if (!nextItem)
				continue;

			m_currentIndex = i;
			nextItem->setSelect(true);
			return;
		}
		currentItem->setSelect(true);
	}

	void right()
	{
		auto currentItem = getItem(m_currentIndex);
		if (currentItem)
		{
			currentItem->setSelect(false);
		}
		for (int i = m_currentIndex  + 1; i < m_items.size(); ++i)
		{
			auto nextItem = getItem(i);
			if (!nextItem)
				continue;

			m_currentIndex = i;
			nextItem->setSelect(true);
			return;
		}
		currentItem->setSelect(true);
	}

	void clearItemStat()
	{
		auto currentItem = getItem(m_currentIndex);
		if (currentItem)
		{
			currentItem->setSelect(false);
		}
	}

	void clearAllItemStat()
	{
		for (auto item : m_items)
		{
			item->setSelect(false);
		}
	}

	void clearAllItems()
	{
		m_items.clear();
	}
private:
	QVector<T*> m_items;
	int m_currentIndex = 0;
};
